package com.wzj.uarmor.interceptor;

import cn.hutool.core.util.StrUtil;
import com.wzj.uarmor.conf.SystemConfig;
import com.wzj.uarmor.exception.BusinessException;
import com.wzj.uarmor.utils.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author whong on 2023/3/17
 * @Description
 */
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    SystemConfig systemConfig;
    @Override
    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object object) throws Exception {
        if (httpRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpResponse.setHeader("Access-control-Allow-Origin", httpRequest.getHeader("Origin"));
            httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
            httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));
            httpResponse.setStatus(HttpStatus.OK.value());
            return true;
        }
        // 从 http 请求头中取出 token
        String token = httpRequest.getHeader("token");
        if(StrUtil.isEmpty(token)){
            throw new BusinessException(ResponseStatus.INVALID_TOKEN);
        }
        Object attribute = httpRequest.getSession().getAttribute(token);
        if(attribute == null){
            throw new BusinessException(ResponseStatus.INVALID_TOKEN);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
